<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- jquery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
        integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
        crossorigin="anonymous"></script>

</head>

<body>
    <div>
        <button type="button" class="btn btn-primary btn-lg mybtn" data-toggle="modal" data-target="#myModal">
            添加商品
        </button>
        <!-- Modal -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="alert alert-success success-div" role="alert">
                商品添加成功
            </div>
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title" id="myModalLabel">
                            添写商品表单
                        </h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-group" id="goodsForm">
                            <div class="form-group has-feedback">
                                <label>商品名称</label>
                                <input type="text" class="form-control" name="goods_name" aria-describedby="商品名称输入正确" />
                                <span class="glyphicon glyphicon-remove form-control-feedback"
                                    aria-hidden="true"></span>
                            </div>
                            <div class="form-group">
                                <label>价格</label>
                                <input type="text" class="form-control" name="price" />
                            </div>
                            <div class="form-group">
                                <label>库存</label>
                                <input type="text" class="form-control" name="stock" />
                            </div>
                            <div class="form-group has-error has-feedback">
                                <label>销量</label>
                                <input type="text" class="form-control" name="sold" />
                                <span class="glyphicon glyphicon-remove form-control-feedback"
                                    aria-hidden="true"></span>
                            </div>
                            <div class="form-group">
                                <label>商品图片</label>
                                <input type="text" class="form-control" name="img"
                                    value="https://img12.360buyimg.com/n7/jfs/t1/185785/38/9092/69871/60c868cbE4edff8f2/ff55da132680832a.jpg" />
                            </div>
                            <div class="form-group">
                                <label>状态</label>
                                <label class="radio-inline">
                                    <input type="radio" name="status" value="1" checked />
                                    上架
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="status" value="2" />
                                    下架
                                </label>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">
                            关闭
                        </button>
                        <button id="addGoods" type="button" class="btn btn-primary">
                            确定添加
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <hr>
        <div class="form-inline">
            <label for="exampleInputEmail1" class="writing">搜索商品</label>
            <input type="search" class="form-control" id="keyword" placeholder="输入商品名称" />
            <button id="btn" class="btn btn-default">搜索</button>
        </div>
    </div>
    <div id="box" class="table-responsive">
        <table class="table table-bordered table-hover table-striped">
            <thead>
                <tr>
                    <th><input type="checkbox" id="all" /></th>
                    <th>ID</th>
                    <th>商品名称</th>
                    <th class="sort-desc">库存</th>
                    <th class="sort-desc">价格</th>
                    <th>状态</th>
                    <th class="sort-desc">销量</th>
                    <th>缩略图</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>

    </div>
    <button style="margin-left: 180px; margin-top: 30px" id="del" class="btn btn-danger">
        批量删除
    </button>
</body>
<style></style>
<script>
    $(function () {
        //显示商品列表
        showGoodsList()
        //添加商品
        $('#addGoods').click(addGoodsFun)

        $('span[aria-hidden="true"]').hide()

        $('input[name="goods_name"]').keyup(checkParams)
        //删除
        $('tbody').click(tbodyClickFun)
        //双击表格修改
        $('tbody').dblclick(EditClickFun)
        //全选
        $('#all').change(allFun)
        //批量删除
        $('#del').click(delCheckFun)
        //搜索
        $('#btn').click(searchFun)
        //库存 价格 销量 排序
        $('.sort-desc').click(sortFun)
    })
    //显示商品列表
    function showGoodsList() {
        $.get(
            'https://liu.zzgoodqc.cn/goods/goodslist',
            function (res) {
                console.log(res)
                if (res.code == 200) {
                    renderGoodsList(res.data)
                }
            },
            'json'
        )
    }
    //渲染商品列表
    function renderGoodsList(data) {
        // data.sort((a, b) => {
        //     return b.id - a.id
        // })
        let html = ''
        data.forEach((item, index) => {
            html += `<tr >
                            <td><input type="checkbox" data-id='${item.id
                }' /></td>
                            <td>${item.id}</td>
                            <td name='edit'>${item.goods_name}</td>
                            <td name='edit'>${item.stock}</td>
                            <td name='edit'>${item.price}</td>
                            <td>${item.status == 1 ? '上架' : '下架'}</td>
                            <td name='edit'>${item.sold}</td>
                            <td>
                                <img  class="img-thumbnail" src="${item.img
                }" alt="" width="100" />
                            </td>
                            <td>${getDate(item.created_at)}</td>
                            <td>
                                <button data-id='${item.id
                }' class="btn btn-info">${item.status == '1' ? '下架' : '上架'
                }</button>
                                <button class="btn btn-danger del" data-id='${item.id
                }'>删除</button>
                                <button class="btn btn-default">编辑</button>
                            </td>
                        </tr>`
        })
        $('tbody').html(html)
    }
    function getDate(n) {
        let date = new Date(n)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    }

    //添加商品
    function addGoodsFun() {
        let formData = $('#goodsForm').serializeArray()
        let data = {}
        formData.forEach((item) => {
            data[item.name] = item.value
        })
        if (!checkParams(data)) {
            return false
        }
        $.post(
            'https://liu.zzgoodqc.cn/goods/add',
            data,
            function (res) {
                if (res.code == 200) {
                    $('.success-div').show('100', function () {
                        showGoodsList()
                        setTimeout(function () {
                            $('.success-div').hide()
                            $('#myModal').modal('toggle')
                        }, 2000)
                    })
                }
            },
            'json'
        )
        console.log(data)
    }
    function checkParams() {
        if (!$('input[name="goods_name"]').val()) {
            $('input[name="goods_name"]')
                .focus()
                .next()
                .removeClass('glyphicon-ok')
                .addClass('glyphicon-remove')
                .show()
                .parent()
                .removeClass('has-success')
                .addClass('has-error')
        } else {
            $('input[name="goods_name"]')
                .focus()
                .next()
                .removeClass('glyphicon-remove')
                .addClass('glyphicon-ok')
                .show()
                .parent()
                .removeClass('has-error')
                .addClass('has-success')
        }
        return true
    }

    //排序
    var sort = {
        stock: 'asc',
        price: 'asc',
        sold: 'asc',
    }
    function sortFun() {
        let con = $(this).html()
        let thisType = null
        if (con == '库存') {
            sort.stock = sort.stock == 'asc' ? 'desc' : 'asc'
            thisType = 'stock'
        } else if (con == '价格') {
            sort.price = sort.price == 'asc' ? 'desc' : 'asc'
            thisType = 'price'
        } else {
            sort.sold = sort.sold == 'asc' ? 'desc' : 'asc'
            thisType = 'sold'
        }
        $.get(
            `https://liu.zzgoodqc.cn/goods/sort?sort=${sort[thisType]}&type=${thisType}`,
            function (res) {
                if (res.code == 200) {
                    renderGoodsList(res.data)
                }
            },
            'json'
        )
    }
    //搜索
    function searchFun() {
        let keyword = $('#keyword').val()
        if (!keyword) {
            showGoodsList()
            return false
        }
        $.ajax({
            url: 'https://liu.zzgoodqc.cn/goods/search',
            type: 'post',
            data: {
                goods_name: keyword,
            },
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    renderGoodsList(res.data)
                }
            },
        })
    }
    //双击编辑表格
    function EditClickFun() {
        //获取到双击的元素对象
        let thisObj = $(event.target)
        //判定是否符合编辑的td框
        if (thisObj[0].nodeName == 'TD' && thisObj.attr('name') == 'edit') {
            //把当前的td框的可编辑属性打开
            thisObj.attr('contenteditable', true)
            //获取焦点
            thisObj.focus()
        }
        //失去焦点时保存数据
        thisObj.blur(function () {
            //获取当前对象的父级的所有子级
            let obj = $(this).parent().children()
            let id = obj.eq(1).html()
            let name = obj.eq(2).html()
            let stock = obj.eq(3).html()
            let price = obj.eq(4).html()
            let status = obj.eq(5).html() == '上架' ? 1 : 2
            let sold = obj.eq(6).html()
            let img = obj.eq(7).children().attr('src')
            let data = {
                id: id,
                goods_name: name,
                stock: stock,
                price: price,
                status: status,
                sold: sold,
                img: img,
            }
            $.post(
                'https://liu.zzgoodqc.cn/goods/update',
                data,
                function (res) {
                    thisObj.attr('contenteditable', false)
                },
                'json'
            )
        })
    }
    //批量删除
    function delCheckFun() {
        $('input:checked').each(function () {
            delGoodsById($(this).attr('data-id'), function () {
                showGoodsList()
            })
        })
    }
    //全选
    function allFun() {
        $('tbody input[type="checkbox"]').prop(
            'checked',
            $(this).prop('checked')
        )
    }
    //删除
    function tbodyClickFun() {
        const delBtn = $(event.target)
        if (delBtn.html() == '删除') {
            let id = delBtn.attr('data-id')
            if (!confirm('确定要删除吗？')) {
                return false
            }
            delGoodsById(id, function () {
                delBtn.parent().parent().remove()
            })
        }
        if (delBtn.html().includes('架')) {
            let status = delBtn.html().includes('下') ? 2 : 1
            let id = delBtn.attr('data-id')
            $.get(
                `https://liu.zzgoodqc.cn/goods/updateStatus?id=${id}&status=${status}`,
                function (res) {
                    if (res.code == 200) {
                        delBtn.html(status == 1 ? '下架' : '上架')
                        delBtn
                            .parent()
                            .parent()
                            .children()
                            .eq(5)
                            .html(status == 1 ? '上架' : '下架')
                    }
                },
                'json'
            )
        }
    }
    function delGoodsById(id, callback) {
        $.get(
            'https://liu.zzgoodqc.cn/goods/delete?id=' + id,
            function (res) {
                if (res.code == 200) {
                    callback(true)
                }
            },
            'json'
        )
    }


</script>
<style>
    #box {
        margin: auto;
        margin-top: 30px;
        width: 1200px;
        height: 500px;
        overflow-y: auto !important;
    }

    td,
    th {
        text-align: center;
    }

    td {
        vertical-align: middle !important;
    }

    thead {
        background-color: rgba(0, 0, 0, 0.5);
        color: white;
        position: sticky;
        top: 0px;
    }

    .mybtn {
        margin-left: 176px;
        margin-top: 20px;
        background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);
        border: none;
        border-radius: 40px;
    }

    .success-div {
        width: 40%;
        text-align: center;
        position: fixed;
        top: 40px;
        left: 33%;
        z-index: 999;
        display: none;
    }

    .form-inline {
        width: 78%;
        height: 60px;
        background-image: linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%);
        margin-left: 170px;
        line-height: 60px;
    }

    .writing {
        font-size: 20px;
        margin-left: 30px;
    }

    .sort-desc {
        cursor: pointer;
        color: #8ec5fc;
    }

    hr {
        height: 1px;
        width: 78%;
        border: none;
        background-color: #ccc;
    }
</style>

</html>